# -*- coding: utf-8 -*-

'''
Created on 09-07-10

@author: peterd
'''


import re

from web.service.LBCParser import LBCParser
from geo.models import NoSuchCity, NoSuchStreet, NoSuchLocation
from infra.logging import logger


class VubParser(LBCParser):
	'''
	classdocs
	'''

	def __init__(self, lbcategory, dataProcessor): 
		LBCParser.__init__(self, lbcategory, dataProcessor)

		self.inAtmRec_ = False
		self.inCity_ = False
		self.inStreet_ = False
		self.lastPage_ = -1
				
		log = logger.getLogger()
		log.debug("%s = %s" % (self, self.__dict__))
		
		
	def reset__(self):		
		LBCParser.reset__(self)


	def start_div(self, attrs):
		for attr, value in attrs:
			if attr == 'class' and value == 'resultsCenter':
				self.inAtmRec_ = True
				
				
	def end_div(self):
		if self.inAtmRec_:
			self.inAtmRec_ = False


	def start_h3(self, attrs):
		if self.inAtmRec_:
			self.inCity_ = True
		
		
	def end_h3(self):
		if self.inCity_:
			self.inCity_ = False


	def start_p(self, attrs):
		if self.inAtmRec_:
			self.inStreet_ = True


	def end_p(self):
		if self.inStreet_:
			self.inStreet_ = False
		
		self.reset__()			


	def start_a(self, attrs):
		if len(attrs) == 1:
			for attr, value in attrs:
				if attr == 'href':
					m = re.search('\?page=([0-9])+', value)
					if m:
						self.lastPage_ = int(m.group(1))

	
	def handle_data(self, data):
		log = logger.getLogger()
		
		data = data.strip()		
		if not data or not self.inAtmRec_:
			return
		
		try:
			if self.inCity_:
				self.setCity(data.split(',')[0].strip())
			if self.inStreet_:
				streetFields = data.split(',')
				if len(streetFields) > 0:
					streetAddr = streetFields[0]
					if len(streetFields) == 2:
						self.building_ = streetFields[1].strip()
					self.setStreet(streetAddr)
					
					if len(self.errors_) == 0:
						self.createOrganization(name = u'VÚB Banka, a.s.', \
								            	url = 'http://www.vub.sk', \
								            	phone = u'služba KONTANT 0850 123 000', \
												logo = 'icons/lbc/atm/vubbanka.png', \
												email = 'kontakt@vub.sk')						
		except NoSuchCity, e:
			log.error('NoSuchCity exception caught, reason: %s' % e)
		except NoSuchStreet, e:
			log.error('NoSuchStreet exception caught, reason: %s' % e)
		except NoSuchLocation, e:
			log.error('NoSuchStreet exception caught, reason: %s' % e)


	def getId(self):
		return self.__class__.__name__
	
	
	def getLastPage(self):
		return self.lastPage_